<template>
  <div class="dashboard">
    <div class="page-header">
      <h2>中医症状汤药管理系统</h2>
      <div class="language-switcher">
        <el-select
          v-model="languageStore.currentLanguage"
          @change="handleLanguageChange"
          style="width: 150px"
        >
          <el-option
            v-for="lang in languageStore.supportedLanguages"
            :key="lang.code"
            :label="lang.nativeName"
            :value="lang.code"
          />
        </el-select>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon category-icon">
                <el-icon><Collection /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.categories || 0 }}</h3>
                <p>症状分类</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon symptom-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.symptoms || 0 }}</h3>
                <p>症状总数</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon formula-icon">
                <el-icon><List /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.formulas || 0 }}</h3>
                <p>汤药总数</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ statistics.activeFormulas || 0 }}</h3>
                <p>启用汤药</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <el-card header="快速操作">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              @click="navigateTo('/admin/symptom-category')"
            >
              <el-icon><Collection /></el-icon>
              管理症状分类
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              type="success"
              size="large"
              style="width: 100%"
              @click="navigateTo('/admin/symptom')"
            >
              <el-icon><Warning /></el-icon>
              管理症状
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              type="warning"
              size="large"
              style="width: 100%"
              @click="navigateTo('/admin/formula')"
            >
              <el-icon><List /></el-icon>
              管理汤药
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 症状测试查询 -->
    <div class="symptom-test">
      <el-card header="症状查询测试">
        <el-form :inline="true" :model="testForm">
          <el-form-item label="输入症状">
            <el-input
              v-model="testForm.symptoms"
              placeholder="请输入症状，用逗号分隔"
              style="width: 300px"
              @keyup.enter="handleSymptomTest"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSymptomTest" :loading="testing">
              查询汤药
            </el-button>
          </el-form-item>
        </el-form>

        <div v-if="testResults.length > 0" class="test-results">
          <h4>查询结果：</h4>
          <el-table :data="testResults" border>
            <el-table-column label="汤药名称" min-width="200">
              <template #default="{ row }">
                <div class="multilang-text">
                  <div><strong>中文:</strong> {{ row.name_zh_cn }}</div>
                  <div><strong>English:</strong> {{ row.name_en_us }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="匹配类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getMatchTypeTag(row.match_type)">
                  {{ getMatchTypeText(row.match_type) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="匹配分数" width="100">
              <template #default="{ row }">
                <el-progress
                  :percentage="Math.round(row.match_score)"
                  :color="getScoreColor(row.match_score)"
                  :show-text="false"
                />
                <span style="margin-left: 8px;">{{ Math.round(row.match_score) }}%</span>
              </template>
            </el-table-column>

            <el-table-column label="主症状" min-width="150">
              <template #default="{ row }">
                <div v-if="row.main_symptoms && row.main_symptoms.length" class="symptom-tags">
                  <el-tag
                    v-for="symptom in row.main_symptoms"
                    :key="symptom.id"
                    type="primary"
                    size="small"
                    class="symptom-tag"
                  >
                    {{ getDisplayName(symptom, 'name') }}
                  </el-tag>
                </div>
                <span v-else class="text-muted">无</span>
              </template>
            </el-table-column>

            <el-table-column label="兼症状" min-width="150">
              <template #default="{ row }">
                <div v-if="row.side_symptoms && row.side_symptoms.length" class="symptom-tags">
                  <el-tag
                    v-for="symptom in row.side_symptoms"
                    :key="symptom.id"
                    type="warning"
                    size="small"
                    class="symptom-tag"
                  >
                    {{ getDisplayName(symptom, 'name') }}
                  </el-tag>
                </div>
                <span v-else class="text-muted">无</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-else-if="testExecuted && testResults.length === 0" class="no-results">
          <el-empty description="未找到匹配的汤药" />
        </div>
      </el-card>
    </div>

    <!-- 最近数据 -->
    <div class="recent-data">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card header="最近添加的症状">
            <el-table :data="recentSymptoms" border max-height="300">
              <el-table-column label="症状名称" min-width="150">
                <template #default="{ row }">
                  {{ getDisplayName(row, 'name') }}
                </template>
              </el-table-column>
              <el-table-column label="分类" width="100">
                <template #default="{ row }">
                  <el-tag type="info" size="small">
                    {{ getDisplayName(row, 'category_name') }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="添加时间" width="140">
                <template #default="{ row }">
                  {{ formatTime(row.created_at) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card header="最近添加的汤药">
            <el-table :data="recentFormulas" border max-height="300">
              <el-table-column label="汤药名称" min-width="150">
                <template #default="{ row }">
                  {{ getDisplayName(row, 'name') }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                    {{ row.is_active ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="添加时间" width="140">
                <template #default="{ row }">
                  {{ formatTime(row.created_at) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Collection,
  Warning,
  List,
  CircleCheck
} from '@element-plus/icons-vue'
import { useLanguageStore } from '@/stores/language'
import { useApi } from '@/composables/useApi'

const router = useRouter()
const languageStore = useLanguageStore()
const { formulaApi, dashboardApi } = useApi()

// 响应式数据
const statistics = reactive({
  categories: 0,
  symptoms: 0,
  formulas: 0,
  activeFormulas: 0
})

const testForm = reactive({
  symptoms: ''
})

const testing = ref(false)
const testExecuted = ref(false)
const testResults = ref([])
const recentSymptoms = ref([])
const recentFormulas = ref([])

// 方法
const getDisplayName = (row, prefix) => {
  const currentLang = languageStore.currentLanguage
  const field = `${prefix}_${currentLang}`
  return row[field] || row[`${prefix}_zh_cn`] || ''
}

const navigateTo = (path) => {
  router.push(path)
}

const handleLanguageChange = (langCode) => {
  languageStore.setLanguage(langCode)
  ElMessage.success(`语言已切换到 ${languageStore.getLanguageName(langCode)}`)
}

const handleSymptomTest = async () => {
  if (!testForm.symptoms.trim()) {
    ElMessage.warning('请输入症状')
    return
  }

  testing.value = true
  testExecuted.value = false

  try {
    const result = await formulaApi.findBySymptoms(testForm.symptoms)

    if (result.code === 0) {
      testResults.value = result.data
      testExecuted.value = true

      if (result.data.length > 0) {
        ElMessage.success(`找到 ${result.data.length} 个匹配的汤药`)
      } else {
        ElMessage.info('未找到匹配的汤药')
      }
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    ElMessage.error('查询失败')
  } finally {
    testing.value = false
  }
}

const getMatchTypeTag = (matchType) => {
  const types = {
    'main_exact': 'success',
    'main_partial': 'primary',
    'side_partial': 'warning'
  }
  return types[matchType] || 'info'
}

const getMatchTypeText = (matchType) => {
  const types = {
    'main_exact': '主症完全匹配',
    'main_partial': '主症部分匹配',
    'side_partial': '兼症匹配'
  }
  return types[matchType] || '未知'
}

const getScoreColor = (score) => {
  if (score >= 80) return '#67c23a'
  if (score >= 60) return '#e6a23c'
  return '#f56c6c'
}

const formatTime = (timeString) => {
  if (!timeString) return '-'

  const date = new Date(timeString)
  const now = new Date()
  const diffMs = now - date
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffMinutes = Math.floor(diffMs / (1000 * 60))

  // 如果是今天
  if (diffDays === 0) {
    if (diffHours === 0) {
      if (diffMinutes === 0) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      }
    } else if (diffHours < 24) {
      return `${diffHours}小时前`
    }
  }
  // 如果是昨天
  else if (diffDays === 1) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  // 如果是一周内
  else if (diffDays < 7) {
    return `${diffDays}天前`
  }
  // 超过一周显示具体日期
  else {
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

const fetchStatistics = async () => {
  try {
    const result = await dashboardApi.getStatistics()
    if (result.code === 0) {
      Object.assign(statistics, result.data)
    } else {
      ElMessage.error(result.msg || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

const fetchRecentData = async () => {
  try {
    // 获取最近的症状
    const symptomResult = await dashboardApi.getRecentSymptoms(5)
    if (symptomResult.code === 0) {
      recentSymptoms.value = symptomResult.data || []
    } else {
      console.error('获取最近症状失败:', symptomResult.msg)
    }

    // 获取最近的汤药
    const formulaResult = await dashboardApi.getRecentFormulas(5)
    if (formulaResult.code === 0) {
      recentFormulas.value = formulaResult.data || []
    } else {
      console.error('获取最近汤药失败:', formulaResult.msg)
    }
  } catch (error) {
    console.error('获取最近数据失败:', error)
    ElMessage.error('获取最近数据失败')
  }
}

// 优化加载 - 使用综合接口
const fetchAllData = async () => {
  try {
    const result = await dashboardApi.getOverview()
    if (result.code === 0) {
      Object.assign(statistics, result.data.statistics)
      recentSymptoms.value = result.data.recentSymptoms || []
      recentFormulas.value = result.data.recentFormulas || []
    } else {
      // 如果综合接口失败，回退到单独获取
      await fetchStatistics()
      await fetchRecentData()
    }
  } catch (error) {
    console.error('获取概览数据失败，尝试单独获取:', error)
    // 回退到单独获取
    await fetchStatistics()
    await fetchRecentData()
  }
}

// 生命周期
onMounted(() => {
  languageStore.initLanguage()
  fetchAllData()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
}

.stats-cards {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.category-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.symptom-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.formula-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.active-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  margin: 0 0 5px 0;
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-info p {
  margin: 0;
  font-size: 16px;
  color: #7f8c8d;
}

.quick-actions {
  margin-bottom: 30px;
}

.symptom-test {
  margin-bottom: 30px;
}

.test-results {
  margin-top: 20px;
}

.test-results h4 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.multilang-text {
  line-height: 1.6;
}

.multilang-text div {
  margin-bottom: 4px;
}

.multilang-text div:last-child {
  margin-bottom: 0;
}

.symptom-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.symptom-tag {
  margin-bottom: 4px;
}

.text-muted {
  color: #999;
}

.no-results {
  margin-top: 20px;
  text-align: center;
}

.recent-data {
  margin-bottom: 30px;
}

.language-switcher {
  display: flex;
  align-items: center;
}

:deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-button--large) {
  padding: 15px 20px;
  font-size: 16px;
  border-radius: 8px;
}
</style>